import jwt
import datetime
from django.conf import settings


header = {
    'alg': 'HS256',  #加密算法
    'typ': 'JWT'    #令牌类型
}

SECRET_KEY = settings.SECRET_KEY  #密钥

class ToolJWT:
    #生成token
    #参数user 为一个字典 {id:username....}
    def gettoken(self,user):
        payload = {
            'userid': user.get("id") ,
            'username': user.get("username",""),   #存储多少个数据 无所谓  但是一定有过期时间
            'headimg' :user.get("headimg"),
            'exp': datetime.datetime.now()+datetime.timedelta(hours=2) #设置过期时间
        }

        return jwt.encode(payload,SECRET_KEY,algorithm='HS256',headers=header)


    def checktoken(self,token):
        # try:
        #     payload = jwt.decode(token,SECRET_KEY,algorithms=['HS256'],headers=header)
        #     return payload
        # except jwt.InvalidTokenError:
        #     raise Exception("token无效")
        # except jwt.ExpiredSignatureError:
        #     raise Exception("token过期")


     payload = jwt.decode(token,SECRET_KEY,algorithms=['HS256'],headers=header)
     return payload

# 自己生成的token
# token='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3MzAzMTA5MTV9.FhdMsU1yukNN3JYD1cj_GfBmEUwI47vbFZiiuntqq3c'

    # 验证token
tooljwt=ToolJWT()


